package com.huynhchihieu.springsecurity.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huynhchihieu.dao.UserDAO;
import com.huynhchihieu.domain.Domainuser;
import com.huynhchihieu.domain.Role;
import com.huynhchihieu.domain.UserRole;
import com.huynhchihieu.service.UserService;
import com.huynhchihieu.springsecurity.dto.CustomUserDetail;

@Service(value = "customUserDetailsService")
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private UserService userService;
	

	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {

		Domainuser domainUser = userDAO.getUser(login);
		//Domainuser domainUser = userDAO.getUserByEmail(login);
		//Domainuser domainUser = userDAO.getUserBySessionFactory(login);
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		return new CustomUserDetail(getAuthorities(domainUser), domainUser.getPassword(), domainUser.getLogin(),
				accountNonExpired, accountNonLocked, credentialsNonExpired, enabled);
	}

	public List<GrantedAuthority> getAuthorities(Domainuser user) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(user));
		return authList;
	}

	public List<String> getRoles(Domainuser user) {
		List<Role> roles= new ArrayList<Role>();// = user.getUserRoles();
		List<UserRole> userRoles = user.getUserRoles();
		for(UserRole userRole : userRoles){
			roles.add(userRole.getRole());
		}
		List<String> roles_String = new ArrayList<String>();
		for (Role role : roles) {
			if (role.getRoleId() == 1) {
				roles_String.add("ROLE_ADMIN");
			} else if (role.getRoleId() == 2) {
				roles_String.add("ROLE_ADMIN");
				roles_String.add("ROLE_MODERATOR");
			}
		}
		return roles_String;
	}

	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}

}
